import axios from 'axios'
import { Message } from 'element-ui'
import router from '@/router'
import { removeToken, getToken } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  withCredentials: true,
  timeout: 500000
})

// axios请求拦截器
service.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers['token'] = token
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// axios响应拦截器
service.interceptors.response.use(
  response => {
    // 如果返回的是二进制数据，直接返回
    if (response.config.responseType === 'blob' || response.config.responseType === 'arraybuffer') {
      return response
    }

    const res = response.data

    // 未登录状态处理
    if (res.code === 0 && res.msg === 'NOT_LOGIN') {
      console.log('用户未登录, 直接跳转至登录页面')
      removeToken()
      router.replace('/login')
      return Promise.reject(new Error('未登录或登录已过期，请重新登录'))
    }

    if (res.code !== 1) {
      // 记录更详细的错误信息
      console.error('API错误:', res)
      Message({
        message: res.msg || '系统错误',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.msg || '系统错误'))
    }

    // 正常响应
    return response
  },
  error => {
    console.log('err' + error)
    let message = error.message

    if (message === 'Network Error') {
      message = '后端接口连接异常'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }

    // 显示错误消息
    Message({
      message,
      type: 'error',
      duration: 5 * 1000
    })

    return Promise.reject(error)
  }
)

export default service
